package config.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import config.annotation.Log;
import logManage.entity.SystemLog;
import logManage.service.SystemLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Aspect
@Slf4j
@Component
public class SysLogAspectAdd {


//    @Resource
	@Autowired
	private SystemLogService systemLogService;

    //切点为controller所有方法
    @Pointcut("@annotation(config.annotation.Log)")
    public void fileLogPointCut() {
    }


    @AfterReturning(returning = "responseDto", pointcut = "fileLogPointCut()")
    public void saveLog(JoinPoint joinPoint, Object responseDto) {
        try {
            saveLog(joinPoint);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

	void saveLog(JoinPoint joinPoint) throws InterruptedException {
		// 1,需要获取用户信息 adminUser
		// if (null != adminUser) {
		Object[] paramsObjArr = joinPoint.getArgs();

		List<Object> paramList = new ArrayList<>();
		for (Object obj : paramsObjArr) {
			if (obj instanceof BindingResult) {
				continue;
			}
			if (obj instanceof MultipartFile) {
				continue;
			}
			if (obj instanceof MultipartFile[]) {
				continue;
			}
			paramList.add(obj);
		}
		String inParamsStr = JSON.toJSONString(paramList, SerializerFeature.WriteDateUseDateFormat);
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		SystemLog systemLog = new SystemLog();
		Log log = method.getAnnotation(Log.class);
		if (log != null) {
			// 注解上的描述
			// System.out.println(syslog.value());
			systemLog.setOperateRecord(log.value());
		}
		// 保存系统日志
		systemLog.setAdminID(1914);// 测试数据
		systemLog.setLoginIp("192.168.31.79");// 测试数据
		systemLog.setLoginTime(new Date());
		systemLog.setOperateTime(new Date());
		systemLog.setConstansRecord(inParamsStr);
		systemLogService.insertLog(systemLog);
		// }
	}
}
